import pygame
import random

# 初始化 Pygame
pygame.init()

# 定义常量
WIDTH = 400
HEIGHT = 400
GRID_SIZE = 4
BLOCK_SIZE = WIDTH // GRID_SIZE
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
COLORS = {
    0: (204, 192, 179),
    2: (238, 228, 218),
    4: (237, 224, 200),
    8: (242, 177, 121),
    16: (245, 149, 99),
    32: (246, 124, 95),
    64: (246, 94, 59),
    128: (237, 207, 114),
    256: (237, 204, 97),
    512: (237, 200, 80),
    1024: (237, 197, 63),
    2048: (237, 194, 46)
}

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2048 游戏")

# 初始化游戏棋盘
board = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]

# 在随机位置生成一个新的 2 或 4
def new_tile():
    empty_cells = [(i, j) for i in range(GRID_SIZE) for j in range(GRID_SIZE) if board[i][j] == 0]
    if empty_cells:
        row, col = random.choice(empty_cells)
        board[row][col] = 2 if random.random() < 0.9 else 4

# 绘制棋盘
def draw_board():
    screen.fill(WHITE)
    for i in range(GRID_SIZE):
        for j in range(GRID_SIZE):
            value = board[i][j]
            pygame.draw.rect(screen, COLORS[value], (j * BLOCK_SIZE, i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
            if value != 0:
                font = pygame.font.Font(None, 50)
                text = font.render(str(value), True, BLACK)
                text_rect = text.get_rect(center=(j * BLOCK_SIZE + BLOCK_SIZE // 2, i * BLOCK_SIZE + BLOCK_SIZE // 2))
                screen.blit(text, text_rect)
    pygame.display.flip()

# 向左移动方块
def move_left():
    moved = False
    for row in board:
        new_row = [x for x in row if x != 0]
        for i in range(len(new_row) - 1):
            if new_row[i] == new_row[i + 1]:
                new_row[i] *= 2
                new_row[i + 1] = 0
        new_row = [x for x in new_row if x != 0]
        new_row.extend([0] * (GRID_SIZE - len(new_row)))
        if new_row != row:
            moved = True
        row[:] = new_row
    return moved

# 向右移动方块
def move_right():
    moved = False
    for row in board:
        new_row = [x for x in row if x != 0]
        new_row.reverse()
        for i in range(len(new_row) - 1):
            if new_row[i] == new_row[i + 1]:
                new_row[i] *= 2
                new_row[i + 1] = 0
        new_row = [x for x in new_row if x != 0]
        new_row.extend([0] * (GRID_SIZE - len(new_row)))
        new_row.reverse()
        if new_row != row:
            moved = True
        row[:] = new_row
    return moved

# 向上移动方块
def move_up():
    moved = False
    for col in range(GRID_SIZE):
        column = [board[row][col] for row in range(GRID_SIZE)]
        new_column = [x for x in column if x != 0]
        for i in range(len(new_column) - 1):
            if new_column[i] == new_column[i + 1]:
                new_column[i] *= 2
                new_column[i + 1] = 0
        new_column = [x for x in new_column if x != 0]
        new_column.extend([0] * (GRID_SIZE - len(new_column)))
        for row in range(GRID_SIZE):
            if new_column[row] != board[row][col]:
                moved = True
            board[row][col] = new_column[row]
    return moved

# 向下移动方块
def move_down():
    moved = False
    for col in range(GRID_SIZE):
        column = [board[row][col] for row in range(GRID_SIZE)]
        column.reverse()
        new_column = [x for x in column if x != 0]
        for i in range(len(new_column) - 1):
            if new_column[i] == new_column[i + 1]:
                new_column[i] *= 2
                new_column[i + 1] = 0
        new_column = [x for x in new_column if x != 0]
        new_column.extend([0] * (GRID_SIZE - len(new_column)))
        new_column.reverse()
        for row in range(GRID_SIZE):
            if new_column[row] != board[row][col]:
                moved = True
            board[row][col] = new_column[row]
    return moved

# 检查游戏是否结束
def is_game_over():
    for i in range(GRID_SIZE):
        for j in range(GRID_SIZE):
            if board[i][j] == 0:
                return False
            if i < GRID_SIZE - 1 and board[i][j] == board[i + 1][j]:
                return False
            if j < GRID_SIZE - 1 and board[i][j] == board[i][j + 1]:
                return False
    return True

# 初始化两个新方块
new_tile()
new_tile()
draw_board()

# 游戏主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            moved = False
            if event.key == pygame.K_LEFT:
                moved = move_left()
            elif event.key == pygame.K_RIGHT:
                moved = move_right()
            elif event.key == pygame.K_UP:
                moved = move_up()
            elif event.key == pygame.K_DOWN:
                moved = move_down()
            if moved:
                new_tile()
                draw_board()
            if is_game_over():
                print("游戏结束！")
                running = False

# 退出游戏
pygame.quit()